const router = require('koa-router')()
const models = require('../models/index')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const qiniu = require('qiniu')

router.post('/login', async ctx => {
    // 用户登录
    let username = ctx.request.body.username
    let password = ctx.request.body.password
    if (username == '' || password == '') {
        return ctx.body = {
            code: 0,
            data: {},
            msg: '请输入用户名或密码!'
        }
    }
    if (username && password) {
        let user = await models.user.findOne({
            where: {
                username,
                password: md5(password),
                lock: '1'
            }
        })
        if (user) {
            const token = jwt.sign({
                username: user.username,
                user_id: user.user_id
            }, 'my_token', {expiresIn: '10h'})
            return ctx.body = {
                code: 200,
                data: {
                    token,
                    user_id: user.user_id,
                    username: user.username,
                    auth: user.auth
                },
                msg: '操作成功!'
            }
        } else {
            return ctx.body = {
                code: 0,
                data: {},
                msg: '密码错误!'
            }
        }
    }  
})
router.post('/get_token', async ctx => {
    var accessKey = 'IPjyn4ydN8QxlXoKyJ8oNY2icvLOw6rBZaBUZp3C';
    var secretKey = 'mEkIkvOaiHpc_FSHxuiiJF1_wBZCibcgfObzkU56';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var options = {
        scope: 'wxhzzzz',
        expires: 36000
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken= putPolicy.uploadToken(mac);
    ctx.body = {
        code: 200,
        data: {
            token: uploadToken
        }
    }
})


module.exports = router